
package com.ldzhao.blog.config.freemarker;

import com.ldzhao.blog.dao.beans.AdvertConfig;
import com.ldzhao.blog.service.AdvertConfigService;
import freemarker.core.Environment;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * <ClassName>AdvertTagDirective</ClassName>
 * <Description>广告</Description>
 *
 * @author liuxianzhao
 * @date 2018/8/8 8:49
 */
@Component
public class AdvertTagDirective implements TemplateDirectiveModel {
    private static final String METHOD_KEY = "method";
    private static final String POSITION_KEY = "positionKey";

    @Autowired
    private AdvertConfigService advertConfigService;

    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
        DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
        if (map.containsKey(METHOD_KEY) && map.containsKey(POSITION_KEY)) {
            String method = map.get(METHOD_KEY).toString();
            String positionKey = map.get(POSITION_KEY).toString();
            switch (method) {
                case "get":
                    AdvertConfig advertConfig = new AdvertConfig();
                    advertConfig.setPositionKey(positionKey);
                    environment.setVariable("advert", builder.build().wrap(advertConfigService.getOneByEntity(advertConfig)));
                    break;
                case "getList":
                    environment.setVariable("advertList", builder.build().wrap(advertConfigService.queryByPositionKey(positionKey)));
                    break;
                default:
                    break;
            }
        }
        templateDirectiveBody.render(environment.getOut());
    }
}
